import 'dart:io';
import 'dart:ui';

import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:restart_app/restart_app.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:signage/app/modules/template/controllers/template_controller.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/edit_dialog.dart';
import 'package:signage/app/utils/http_client.dart';

class ProfileController extends GetxController {
  //TODO: Implement ProfileController

  final HttpClient _httpClient = HttpClient();
  final count = 0.obs;
  final userInfo = UserInfo().obs;
  final RxString currentLanguage = ''.obs;

  @override
  void onInit() async {
    super.onInit();
    tempDirSize();
    // 从本地存储获取语言设置
    final prefs = await SharedPreferences.getInstance();
    final savedLanguage = prefs.getString('app_language');
    if (savedLanguage != null) {
      currentLanguage.value = savedLanguage;
      // 应用保存的语言设置
      if (savedLanguage.isEmpty) {
        Get.updateLocale(Get.deviceLocale ?? const Locale('en'));
      } else {
        Get.updateLocale(Locale(savedLanguage));
      }
    } else {
      currentLanguage.value = Get.locale?.languageCode ?? '';
    }
  }

  @override
  void onReady() async {
    super.onReady();
    await getUserInfo();
  }

  Future<void> getUserInfo() async {
    final value = await _httpClient.getUserInfo();
    userInfo.value = value.userInfo ?? UserInfo();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void increment() => count.value++;

  Future<void> onAccountTap() async {
    // TODO: 实现账号管理功能
    // Get.toNamed(Routes.ACCOUNT);
    print('onAccountTap');
    final result =
        await Get.toNamed(Routes.FONT_MANAGER, arguments: {'selectMode': true});
    if (result != null) {
      print('选中的字体：${result.name}');
    }
  }

  void onListManagementTap() {
    // TODO: 实现名单管理功能
    Get.toNamed(Routes.CHOOSE_LIST);
  }

  void onFontManagementTap() {
    // TODO: 实现字体管理功能
    Get.toNamed(Routes.FONT_MANAGER);
  }

  void onScreenRecordTap() {
    // TODO: 实现投屏记录功能
    Get.toNamed(Routes.CAST_RECORD);
  }

  void onTransferSettingsTap() {
    // Get.toNamed(Routes.TRANSFER_SETTINGS);
    Get.toNamed(Routes.TRANSFER);
  }

  void onClearCacheTap() {
    // TODO: 实现清除缓存功能
    Get.dialog(TipsDialog(
      title: AppLocalizations.of(Get.context!)!.translate('tips'),
      text: AppLocalizations.of(Get.context!)!.translate('confirm_clear_cache'),
      onConfirm: () async {
        Get.back();
        final tempDir = await getTemporaryDirectory();
        tempDir.delete(recursive: true);
        tempDirSize();
        EasyLoading.showSuccess(AppLocalizations.of(Get.context!)!
            .translate('clear_cache_success'));
      },
    ));
  }

  void onFirmwareUpgradeTap() {
    // TODO: 实现固件升级功能
    Get.toNamed(Routes.OTA);
  }

  void tempDirSize() async {
    final tempDir = await getTemporaryDirectory();
    if (tempDir.existsSync()) {
      final totalSize = await getTotalSizeOfFilesInDir(tempDir);
      print('临时目录大小：${totalSize / 1024 / 1024} MB');
      totalSizeStr.value = '${(totalSize / 1024 / 1024).toStringAsFixed(2)} MB';
    } else {
      totalSizeStr.value = '0.00 MB';
    }
  }

  final totalSizeStr = '0'.obs;

  static Future<double> getTotalSizeOfFilesInDir(
      final FileSystemEntity file) async {
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      double total = 0;
      if (children != null)
        for (final FileSystemEntity child in children)
          total += await getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }

  void onLogoutTap() async {
    Get.dialog(TipsDialog(
      title: AppLocalizations.of(Get.context!)!.translate('tips'),
      text: AppLocalizations.of(Get.context!)!.translate('confirm_logout'),
      cancelText: AppLocalizations.of(Get.context!)!.translate('cancel'),
      showCancel: true,
      onConfirm: () async {
        Get.back();
        try {
          await _httpClient.logout();
        } catch (e) {
          print('退出登录失败：$e');
        }
        SpUtil.clearStoredUid();
        SpUtil.remove('token');
        Get.offAllNamed(Routes.LOGIN);
      },
    ));
  }

  void onLogoutTap2() async {
    Get.dialog(TipsDialog(
      title: AppLocalizations.of(Get.context!)!.translate('tips'),
      text: AppLocalizations.of(Get.context!)!.translate('confirm_logout'),
      cancelText: AppLocalizations.of(Get.context!)!.translate('cancel'),
      showCancel: true,
      onConfirm: () async {
        Get.back();
        try {
          await _httpClient.logout();
        } catch (e) {
          print('退出登录失败：$e');
        }
        SpUtil.clearStoredUid();
        SpUtil.clearUserData();
        Get.offAllNamed(Routes.LOGIN);
      },
    ));
  }

  String getCurrentLanguage() {
    switch (currentLanguage.value) {
      case 'zh':
        return '中文';
      case 'en':
        return 'English';
      default:
        return '跟随系统';
    }
  }

  void changeLanguage(String? languageCode) async {
    if (languageCode == null) {
      Get.updateLocale(Get.deviceLocale ?? const Locale('en'));
      currentLanguage.value = '';
    } else {
      Get.updateLocale(Locale(languageCode));
      currentLanguage.value = languageCode;
    }

    // 保存语言设置到本地存储
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('app_language', currentLanguage.value);

    // 重新加载模板
    final templateController = Get.find<TemplateController>();
    templateController.loadTemplates();

    // 强制更新整个应用
    Restart.restartApp(
      /// In Web Platform, Fill webOrigin only when your new origin is different than the app's origin
      // webOrigin: 'http://example.com',

      // Customizing the restart notification message (only needed on iOS)
      notificationTitle: 'Restarting App',
      notificationBody: 'Please tap here to open the app again.',
    );
  }
}
